<template>
  <a-row :gutter="10">
    <a-col :md="7" :sm="24" v-if="!disabled" style="overflow-y: auto; max-height: 80vh;">
      <address-list-left ref="addresslist" @input="treeChoose"/>
    </a-col>
    <!-- 中间区域 -->
    <a-col :md="8" :sm="24" v-if="!disabled">
      <a-form layout="inline" @keyup.enter.native="search">
        <a-row :gutter="10">
          <a-form-item label="用户姓名">
            <a-input placeholder="请输入用户姓名" v-model="realName" />
          </a-form-item>
          <a-form-item>
            <a-button @click="search" icon="search">查询</a-button>
          </a-form-item>
        </a-row>
      </a-form>

      <div class="item-btn-mar">
        <a-table
          ref="table"
          size="middle"
          rowKey="empId"
          bordered
          :scroll="{ y: '80vh' }"
          :columns="columns"
          :dataSource="midDataSource"
          :pagination="ipagination"
          :loading="midLoading"
          :rowSelection="{selectedRowKeys: selectedRowKeys,onSelect:onSelect,onSelectAll:onSelectAll,getCheckboxProps:record => ({
            props: {
              disabled: record.disabled
            }
          })}"
          @change="handleTableChange">

        </a-table>
      </div>
    </a-col>
    <!-- 右侧区域 -->
    <a-col :md="md" :sm="24">
      <div style="height:40px;font-size:16px;display: flex;justify-content: space-between;align-items: center;">
        <span>已选人员</span>
      </div>
      <div class="item-btn-mar">
        <a-table
          ref="table"
          size="middle"
          rowKey="empId"
          bordered
          :scroll="{ y: 800 }"
          :columns="columns"
          :dataSource="selectionRows"
          :pagination="false"
          :loading="rightLoading">

        </a-table>
      </div>
    </a-col>
  </a-row>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import AddressListLeft from '@/views/system/modules/AddressListLeft.vue'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'TeamChoose',
  components: { AddressListLeft },
  props: {
    // 只查看，不能操作
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    publishId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      collKey: '1',
      leftListUrl: '/api/erp/omc/teammanager/erpOmcTeamManager/list', // 左侧树的list
      findEmpUser: '/api/erpmng/sys/user/queryByOrgCodeForAddressList', // 中间获取list
      noticeId: '', // 公告id
      teamId: '', // 团队id
      orgCode: '', // 团队orgCode
      realName: '',
      leftLoading: false,
      midLoading: false,
      rightLoading: false,
      columns: [
        {
          title: '序号',
          width: 60,
          dataIndex: 'id',
          align: 'center',
          customRender: function (t, r, index) {
          return parseInt(index) + 1;
          }
        },
        {
          title: '用户部门',
          align: 'center',
          dataIndex: 'departId',
          ellipsis: true,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['departId'], text + '')
            }
          }
        },
        {
          title: '用户姓名',
          align: 'center',
          dataIndex: 'employeeId',
          ellipsis: true,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['employeeId'], text + '')
            }
          }
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '100'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      leftDataSource: [], // 左侧的list data
      midDataSource: [], // 中间
      selectionRows: [], // 右侧选中的item
      selectedRowKeys: [], // 是否选择的keys
      md: 9,
      selectDataList: [], // 获取之前已经选的人
      firstSelectData: [], // 保存一开始的已选人员
      form: {},
      validatorRules: {
        groupName: [
          { required: true, message: '请输入小组名称!' }
        ]
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      groupId: '',
      isSubmit: false,
      dictOptions: {}
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    search() {
      if (this.collKey == '1') {
        this.getmidList()
      } else {
        this.getmidList2()
      }
    },
    initDictConfig() {
      // 姓名
      initDictOptions('erp_employee_file,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'employeeId', res.result)
        }
      })
      // 部门
      initDictOptions('sys_depart,depart_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'departId', res.result)
        }
      })
    },
    handleTableChange(pagination) {
      this.ipagination.current = pagination.current;
      this.ipagination.pageSize = pagination.pageSize;
      this.search()
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.formss.validate((valid) => {
        if (valid) {
          this.isSubmit = true
          this.form.groupMembers = this.selectionRows.map(v => v.empId).join(',')
          httpAction('/api/erp/publish/erpPublishContactGroup/add', this.form, 'post')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                if (that.collKey == '2') {
                  that.$refs.grouplist.commonRequestThen('')
                }
              } else {
                that.$message.warning(res.message)
              }
              that.isSubmit = false
            })
        }
      })
    },
    callback() {
      if (this.collKey == '1') {
        this.$refs.addresslist.queryTreeData()
      } else {
        this.$nextTick(() => {
          this.$refs.grouplist.commonRequestThen('')
        })
      }
    },
    // 左侧树选择
    treeChoose(orgCode) {
      this.orgCode = orgCode
      this.ipagination.current = 1
      this.getmidList()
    },
    groupChoose(id) {
      this.groupId = id || ''
      this.ipagination.current = 1
      if (id) {
        this.getmidList2()
      } else {
        this.midDataSource = []
        this.ipagination.total = 0
      }
    },
    // 单选
    onSelect(record) {
      console.log('------炸裂走了', record)
      if (this.selectedRowKeys.includes(record.employeeId)) {
        this.selectedRowKeys = this.selectedRowKeys.filter(it => it != record.employeeId)
        this.selectionRows = this.selectionRows.filter(it => it.employeeId != record.employeeId)
      } else {
        this.selectedRowKeys.push(record.employeeId)
        this.selectionRows.push(record)
      }
    },
    // 全选
    onSelectAll(selected, selectedRows) {
      console.log('------炸裂走了')
      if (selected) {
        let listAll = JSON.parse(JSON.stringify(this.selectionRows))
        listAll = listAll.concat(this.midDataSource)
        // 去重
        listAll = listAll.filter((item) => !listAll.includes(item.employeeId) && listAll.push(item.employeeId))

        listAll = listAll.filter(r => !r.disabled)

        this.selectionRows = listAll
        this.selectedRowKeys = listAll.map(rr => {
          return rr.employeeId
        })
      } else {
        for (let it of this.midDataSource) {
          this.selectionRows = this.selectionRows.filter(rr => rr.employeeId != it.employeeId)
          this.selectedRowKeys = this.selectedRowKeys.filter(rr => rr != it.employeeId)
        }
      }
      },
    // 左侧团队-分页列表查询
    async getLeftChangeList() {
      this.leftDataSource = []
      this.midDataSource = [] // 进来先清空list里数据

      this.leftLoading = true
      let params = {
        pageNo: 1,
        pageSize: -1,
        tdnd: moment().format('YYYY'),
        teamLevel: '1'
      }
      let res = await getAction(this.leftListUrl, params)
      if (res.success) {
        const { records, current, total } = res.result

        this.leftDataSource = records
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.leftDataSource = []
      }
      this.leftLoading = false
    },
    // 获取选中的人
    async getSelectDataList() {
      // 判断是通知公告or意见征集
      // let url = `/api/erp/${this.formType === 'opinion' ? 'publishCollect' : 'publishNotice'}/findDeptSelectEmpUser`
      let params = {
        noticeId: this.publishId,
        collectId: this.publishId,
        orgCode: this.orgCode,
        pageNo: 1,
        pageSize: -1
      }
      let res = await getAction(url, params)

      if (res.success) {
        this.selectDataList = res.result.records || []
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.selectDataList = []
      }
    },
    // 中间查询用户信息-列表
    async getmidList2() {
      console.log('------炸裂走了')
      this.midLoading = true
      let params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        realName: this.realName,
        id: this.groupId
      }
      let res = await getAction('/api/erp/publish/erpPublishContactGroup/queryEmpByGroupId', params)
      if (res.success) {
        let { records, current, total } = res.result

        this.ipagination.total = total || 0

        this.midDataSource = records.map(r => {
          return {
            // id: r.userId,
            disabled: false,
            ...r
          }
        })
        // 获取数据回显
        if (this.selectionRows.length !== 0) {
          for (let it of this.midDataSource) {
            for (let ii of this.selectedRowKeys) {
              if (ii == it.empId) {
                it.disabled = false
                this.selectionRows.push(it)
              }
            }
          }
        } else {
          this.selectedRowKeys = []
        }
        this.selectionRows = this.selectionRows.filter((item) => !this.selectionRows.includes(item.empId) && this.selectionRows.push(item.empId))
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.midDataSource = []
      }
      this.midLoading = false
    },
    // 中间查询用户信息-列表
    async getmidList() {
      console.log('------炸裂走了')
      this.midLoading = true
      // await this.getSelectDataList()
      let params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        realname: this.realName,
        orgCode: this.orgCode
      }
      let res = await getAction(this.findEmpUser, params)
      if (res.success) {
        let { records, current, total } = res.result

        this.ipagination.total = total || 0
        console.log('----records', records)
        this.midDataSource = records.map(r => {
          return {
            id: r.empId,
            disabled: false,
            ...r,
            departId: r.departIds,
            employeeId: r.empId,
            linkTel: r.phone
          }
        })
        console.log('selectionRows', this.selectionRows)
        console.log('selectedRowKeys', this.selectedRowKeys)
        // 获取数据回显
        if (this.selectionRows.length !== 0) {
          for (let it of this.midDataSource) {
            for (let ii of this.selectedRowKeys) {
              if (ii == it.empId) {
                it.disabled = false
                // this.selectionRows.push(it)
              }
            }
          }
        } else {
          this.selectedRowKeys = []
        }
        // this.selectionRows = this.selectionRows.filter((item) => !this.selectionRows.includes(item.empId) && this.selectionRows.push(item.empId))
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.midDataSource = []
      }
      this.midLoading = false
    }
  }
}
</script>
<style lang="less">

  .item-btn-mar{
    position: relative;
    height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
